package com.xingda.packing.task.handle;

import com.xingda.packing.common.PackUtils;
import com.xingda.packing.domain.PackProductionLine;
import com.xingda.packing.domain.Robot;
import com.xingda.packing.domain.Wheel;
import com.xingda.packing.enums.*;
import com.xingda.packing.http.WheelHttp;
import com.xingda.packing.task.ticket.ScanCodeTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ScanCodeHandle implements TaskHandleService {
    @Override
    public boolean accept(PackProductionLine productionLine, int area) {
        return checkTask(productionLine.getRobot().getTaskTicket(area), TaskType.SCANCODE);
    }

    @Override
    public void process(PackProductionLine productionLine, int area) {
        ScanCodeTicket ticket = (ScanCodeTicket) productionLine.getRobot().getTaskTicket(area);
        Robot robot = productionLine.getRobot();
        if (!robot.isScanSignal(area)) {
            log.info("区域{}->条形码读取触发为FALSE", area);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        if (robot.getStopStatus(area)) {
            log.info("区域{}->机器人被强制停止", area);
            return;
        }
        String scanWheelNo = productionLine.getRobot().getScanWheelNo(area);
        log.info("区域{}->_______________scanWheelNo1 :{}", area, scanWheelNo);
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (Exception e) {
            log.error("=====ScanCodeHandle的process sleep error", e);
        }

        scanWheelNo = productionLine.getRobot().getScanWheelNo(area);
        productionLine.getRobot().saveVisualSense(scanWheelNo, area);
        log.info("区域{}->_______________scanWheelNo2 :{}", area, scanWheelNo);
        Wheel wheel;
        int productType = productionLine.getRobot().getProductTypeToZeroGrab(area, ticket.getLocationNo());

//        测试用  -- 高低轮
        log.info("==== 高低轮的类型:{}", productType);

        if (productType == 0) {
            log.error("区域{},产品类别为{}", area, productType);
            productionLine.getRobot().createAlarmEvent("抓取位从PLC未读取到产品类别", area);
            productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.NO_PRODUCT_TYPE, true, area);
            stopTask(productionLine, area);
            return;
        }
        if (StringUtils.hasText(scanWheelNo)) {
            String ab = scanWheelNo.substring(0, 1);
            log.info("区域{},PLC读取颜色为{}", area, ab);
            String wheelNo = scanWheelNo.substring(1).replaceAll("#+$", "").replaceAll("X+$", "");
            log.info("区域{},PLC读取的条码{}", ab, wheelNo);
            if (ab.equals("#")) {
                //颜色没识别
                wheel = PackUtils.createEmptyWheel(productType, new BigDecimal("99"));
                productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.WHEEL_ERROR_99, true, area);
                productionLine.getRobot().createAlarmEvent("抓取位颜色未识别,已停止系统", area);
            } else if (wheelNo.isEmpty()) {
                //条码没识别
                wheel = PackUtils.createEmptyWheel(productType, new BigDecimal("99"));
                productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.WHEEL_ERROR_99, true, area);
                productionLine.getRobot().createAlarmEvent("抓取位条码未识别,已停止系统", area);
            } else {
                //颜色条码都识别
                wheel = WheelHttp.queryIntermediateVO(wheelNo, productType);

//                颜色改判
                if (wheel.getVFree2().equals("B80") && ab.equals("D")) {
                    //B80识别为粉色的 改判为红
                    ab = "A";
                }
                if (wheel.getVFree2().equals("B40") && ab.equals("A")) {
                    //B40识别为红色的 改判为粉
                    ab = "D";
                }
                if (wheel.getVFree2().equals("B80/17") && ab.equals("A")) {
                    //B80/17识别为红色的 改判为粉
                    ab = "D";
                }
                if (wheel.getVFree2().equals("B60") && ab.equals("D")) {
                    //B60识别为粉色的 改判为红
                    ab = "A";
                }

                if (!isConsistent(wheel, productType)) {
                    wheel = PackUtils.createEmptyWheel(productType, new BigDecimal("99"));
                    productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.PRODUCT_TYPE_ERROR, true, area);
                    productionLine.getRobot().createAlarmEvent("抓取位工字轮查询产品类别" + wheel.getVFree2() + "和PLC反馈" + productType + "不符合,已停止系统", area);
                }
                BigDecimal torsionValue = wheel.getTorsionValue();
                if (torsionValue.compareTo(BigDecimal.valueOf(999.0)) == 0 && Objects.isNull(wheel.getConsumerName())) {
                    //触发报警
                    productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.WHEEL_ERROR_999, true, area);
                    productionLine.getRobot().createAlarmEvent("网络异常,已停止系统", area);
                } else if (torsionValue.compareTo(BigDecimal.valueOf(9999.0)) == 0 && Objects.isNull(wheel.getConsumerName())) {
                    //触发报警
                    productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.WHEEL_ERROR_9999, true, area);
                    productionLine.getRobot().createAlarmEvent("未查到工字轮信息,已停止系统,工字轮轮号:" + wheelNo, area);
                } else {
                    if (wheel.getBarCode().startsWith("XD")) {
                        if (Objects.isNull(wheel.getFixedLength())) {
                            productionLine.getRobot().createAlarmEvent("工字轮没有定长信息" + wheelNo, area);
//                            八厂是999999
                            wheel.setWheelTag("NOT-" + robot.getInvNameByInvBasDoc(wheel.getPkInvbasdoc()) + "-" + wheel.getVFree2() + "-" + 10600);
                        } else {
                            wheel.setWheelTag("NOT-" + robot.getInvNameByInvBasDoc(wheel.getPkInvbasdoc()) + "-" + wheel.getVFree2() + "-" + wheel.getFixedLength());
                        }
                    } else {
                        if (Objects.isNull(wheel.getFixedLength())) {
                            productionLine.getRobot().createAlarmEvent("工字轮没有定长信息" + wheelNo, area);
                            wheel.setWheelTag(robot.getInvNameByInvBasDoc(wheel.getPkInvbasdoc()) + "-" + wheel.getVFree2() + "-" + 10600 + "-" + WheelSurfaceType.getByAB(ab).getGr());
                        } else {
                            wheel.setWheelTag(robot.getInvNameByInvBasDoc(wheel.getPkInvbasdoc()) + "-" + wheel.getVFree2() + "-" + wheel.getFixedLength() + "-" + WheelSurfaceType.getByAB(ab).getGr());
                        }
                    }
                }
                if (wheelNo.length() == 13) {
                    wheelNo = wheelNo + "#####_" + ab;
                }
                if (wheelNo.length() == 16) {
                    wheelNo = wheelNo + "##_" + ab;
                }
                if (Objects.isNull(wheel.getFixedLength())) {
                    wheel.setWheelTagMap(robot.getInvNameByInvBasDoc(wheel.getPkInvbasdoc()) + "-" + wheel.getVFree2() + "-" + 10600);
                } else {
                    wheel.setWheelTagMap(robot.getInvNameByInvBasDoc(wheel.getPkInvbasdoc()) + "-" + wheel.getVFree2() + "-" + wheel.getFixedLength());
                }
                wheel.setBarCodeBack(wheelNo);
                wheel.setAb(ab);
                wheel.setArea(area);
            }
        } else {
            //创建异常轮
            wheel = PackUtils.createEmptyWheel(productType, new BigDecimal("99"));
            productionLine.getRobot().createAlarmEvent("PLC读取的信息为空,已停止任务", area);
        }
        //条码信息
        if (wheel.getBarCode().startsWith("XC") && !wheel.isAvailable()) {
            productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.SHUNT_AREA_WHEEL_NO_AVAILABLE, true, area);
            productionLine.getRobot().createAlarmEvent("工字轮条码为成品,查询信息为不合格品,已停止系统,工字轮条码:" + wheel.getBarCode(), area);
            stopTask(productionLine, area);
            return;
        }
        robot.resetPackingStatus(area, wheel.getBarCode());
        if (wheel.getState() == WheelUseState.PACK_BOX.getNumber()) {
            log.info("工字轮已装箱,信息已上传,已停止系统,工字轮条码:" + wheel.getBarCode());
            productionLine.getRobot().createAlarmEvent("工字轮已装箱,信息已上传,已停止系统,工字轮条码:" + wheel.getBarCode(), area);
            stopTask(productionLine, area);
            return;
        }
        //重复装箱
        if (!robot.getTagValue(area)) {
            robot.checkPackingStatus(area, wheel.getBarCode());
        }
        if (robot.getAlreadyPackingStatus(area)) {
            productionLine.getRobot().createAlarmEvent("工字轮已装箱,已停止系统,工字轮条码:" + wheel.getBarCode(), area);
            stopTask(productionLine, area);
            return;
        }
        robot.putWheel(wheel, area);
        if (!wheel.getQualityState().equals(WheelQualityState.QUALITY)) {
            if (wheel.getVFree2().equals("B40") || wheel.getVFree2().equals("B60")) {
                wheel.setWheelTag("ERROR-B40-B60");
                wheel.setWheelTagMap("ERROR-B40-B60");
            } else {
                wheel.setWheelTag("ERROR-B80-B80/17");
                wheel.setWheelTagMap("ERROR-B80-B80/17");
            }
            productionLine.getRobot().createAlarmEvent("工字轮条码为成品,查询信息为不合格品,工字轮条码:" + wheel.getBarCode(), area);
        }
        robot.checkColorByRobotAndShuntArea(area, wheel);
        if (wheel.getTorsionValue().compareTo(BigDecimal.valueOf(10.0)) < 0) {
            if (!robot.getConfirm(area)) {
                robot.grabWheel(area);
                robot.receive(productType, area);
                ticket.setState(TaskState.RUNING);
                ticket.setWheel(wheel);
                // 事件保存,读码完成
                robot.handleScanCodeEvent(ticket, area);
                robot.initAlarm(area);
            }
        } else {
            stopTask(productionLine, area);
        }
    }

    private boolean isConsistent(Wheel wheel, int productType) {
        if (wheel.getVFree2().startsWith("B80") && productType == 2) {
            return true;
        }
        return wheel.getVFree2().equals("B40") || wheel.getVFree2().equals("B60") && productType == 1;
    }

    public void stopTask(PackProductionLine packProductionLine, int area) {
        ScanCodeTicket ticket = (ScanCodeTicket) packProductionLine.getRobot().getTaskTicket(area);
        ticket.setState(TaskState.FINISH);
        packProductionLine.setInitRunning(area, false);
        packProductionLine.getRobot().setTaskTicket(ticket, area);
        packProductionLine.getRobot().clear(area);
    }
}
